package protocol.work.connection;

import org.apache.commons.logging.Log;

import protocol.common.util.CJLog;
import protocol.common.util.StringKit;
import protocol.data.util.JedisPoolUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public abstract class AbstractConnection extends Thread{
	protected Log logger = CJLog.getLogConsole();
	
	/**
	 * 初始化标识
	 * */
	protected boolean initMark;
	
	
	protected JedisPool jedisPool;
	
	public AbstractConnection(String channel){
		this.jedisPool = JedisPoolUtil.getJedisPool();
	}
	
	public void exceptionHandle(Exception ex){
		logger.error(StringKit.getExceptionInfo(ex));
	}
	
	public void threadSleep(Long second){
		try {
			sleep(second);
		} catch (InterruptedException e) {
			this.exceptionHandle(e);
		}
	}
	
	public void threadSleep(){
		this.threadSleep(1000L);
	}
	
	public void stopThread() {
		this.initMark = false;
	}

	public void setThreadKey(String key){
		super.setName(key);
	}
	
	protected void returnJedis(Jedis jedis) {
		if (jedis != null)
			if (jedis.isConnected())
				this.jedisPool.returnResource(jedis);
			else
				this.jedisPool.returnBrokenResource(jedis);
	}

	protected Jedis getJedis() {
		return (Jedis) this.jedisPool.getResource();
	}
	
}
